/**业务管理流程平台版本1.0,生成时间:2017-04-13 13:16:48**/
package com.xbdun.service.bmp.service.system.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.xbdun.common.api.Client;
import com.xbdun.common.enums.UserRolesEnums;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.common.page.Pager;
import com.xbdun.dao.bmp.entity.XbdunRoleDo;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.request.system.RolePagerRequest;
import com.xbdun.facade.bmp.request.system.RoleRequest;
import com.xbdun.facade.bmp.response.system.RoleResponse;
import com.xbdun.service.bmp.biz.OrgUserBiz;
import com.xbdun.service.bmp.biz.RoleBiz;
import com.xbdun.service.bmp.service.system.RoleService;

import lombok.extern.slf4j.Slf4j;

/**
 * 企业信息
 * 
 * @ClassName RoleServiceImpl
 * @author 张国涛 @2017-04-13 13:16:48
 */
@Service
@Transactional
@Slf4j
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleBiz roleBiz;
	@Autowired
	OrgUserBiz orgUserBiz;
	/**
	 * 新增角色
	 * 
	 * @param request
	 */
	public Long addRole(RoleRequest request,Client client) throws Exception {
		XbdunRoleDo xbdunRoleDo = new XbdunRoleDo();
		
		xbdunRoleDo.setOrgCode(client.getOrgCode());
		xbdunRoleDo.setRoleName(request.getRoleName());
		xbdunRoleDo.setRoleShort(request.getRoleShort());
		xbdunRoleDo.setOptionUser(client.getUserName());
		xbdunRoleDo.setCreateTime(new Date());
		
		long xbdunOrgCode = orgUserBiz.getXbdunOrgCode();
		if (roleBiz.existRoleInOrg(xbdunRoleDo.getOrgCode(),xbdunOrgCode,xbdunRoleDo.getRoleName()) > 0) {
			throw BmpBizException.DATA_EXIST.newInstance("已经存在" + xbdunRoleDo.getRoleName() + "角色");
		}
		
		log.info("新增角色信息 {}" , JSON.toJSONString(xbdunRoleDo));
		
		Long addXbdunRoleInfo = roleBiz.addXbdunRole(xbdunRoleDo);
		if (null == addXbdunRoleInfo || addXbdunRoleInfo.longValue() <= 0) {
			throw BmpBizException.DB_INSERT_RESULT_0;
		}
		return addXbdunRoleInfo;
	}

	
	/**
	* @Title: modifyRole
	* @Description: 修改角色信息
	* @param request	角色信息
	* @throws Exception
	 */
	@Transactional
	public void modifyRole(RoleRequest request,Client client)throws Exception{
		//查询当前角色所属机构
		Long orgCode = roleBiz.getOrgCodeById(request.getId());
		if (orgCode != client.getOrgCode()) {
			throw BizException.POWER_FAIL.newInstance("对不起当前角色属于平台机构,您没有权限修改");
		}
		XbdunRoleDo xbdunRoleDo = new XbdunRoleDo();
		xbdunRoleDo.setId(request.getId());
		xbdunRoleDo.setRoleName(request.getRoleName());
		xbdunRoleDo.setRoleShort(request.getRoleShort());
		xbdunRoleDo.setOptionUser(client.getUserName());
		roleBiz.updateById(xbdunRoleDo);
	}
	
	/**
	* @Title: getRole
	* @Description: 根据角色ID查询角色信息
	* @param id	角色ID
	* @return RoleResponse    返回类型
	* @throws
	 */
	public RoleResponse getRole(long id)throws Exception{
		if (id <= 0 ) throw BizException.PARAM_CHKE_FAIL.newInstance("角色ID不能小于等于零");
		
		XbdunRoleDo xbdunRoleById = roleBiz.getXbdunRoleById(id);
		if ( null == xbdunRoleById ) {
			throw BizException.DB_SELECTONE_IS_NULL;
		}
		
		// 资源Copy
		RoleResponse response = new RoleResponse();
		BeanUtils.copyProperties(response, xbdunRoleById);
		return response;
	}
	/**
	* @Title: queryPager
	* @Description: 加载自己和平台已经设置好的角色
	* @param requestPager	请求参数
	* @return Pager<SysOrgResponse>    返回类型
	 */
	public Pager<RoleResponse> queryPager(RolePagerRequest request,Client client) throws Exception{
		Map<String,Object> where  = new HashMap<String,Object>();
		long xbdunOrgCode = orgUserBiz.getXbdunOrgCode();
		if (StringUtils.isNotBlank(request.getRoleName())) {
			where.put("roleName",request.getRoleName());
		}
		if (StringUtils.isNotBlank(request.getRoleShort())) {
			where.put("roleShort",request.getRoleShort());
		}
		//排序
		if(StringUtils.isBlank(request.getOrderBy())){
			request.setOrderBy(" createTime ASC");
		}
		
		// 如果是超级管理，那么他只能看见管理员的，
		//加载自己机构和平台角色下的角色
		if(xbdunOrgCode!=client.getOrgCode()){
			where.put("orgCode",new Long[]{client.getOrgCode(),xbdunOrgCode});
			if(UserRolesEnums.isSupperAdmin(client.getRoleId())||UserRolesEnums.isAdmins(client.getRoleId())){
				//是超级管理员
				where.put("notEqtId",new Long[]{(long) UserRolesEnums.XBDADMINT.getKey(),(long) UserRolesEnums.SUPPERADMIN.getKey()});
			}else{
				//其他人就必须排除所有角色
				where.put("notEqtId",new Long[]{(long) UserRolesEnums.XBDADMINT.getKey(),(long) UserRolesEnums.SUPPERADMIN.getKey(),(long) UserRolesEnums.ADMIN.getKey()});
			}
		}else{
			//只显示平台角色
			where.put("orgCode",new Long[]{client.getOrgCode(),0L});
		}
		Pager<RoleResponse> queryPager = roleBiz.queryPager(where, request.getOrderBy(),request.getPageIndex(), request.getPageSize());
		where.clear();
		where = null;
		return queryPager;
	}


	public void deleteRole(Long id, Client client) throws Exception {
		//获取该角色的version
		Timestamp version = roleBiz.getVersionById(id);
		if (version == null){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("当前角色不存在");
		}
		//查询当前角色所属机构
		Long orgCode = roleBiz.getOrgCodeById(id);
		if (orgCode != client.getOrgCode()) {
			throw BizException.POWER_FAIL.newInstance("对不起当前角色属于平台机构,您没有权限删除");
		}
		
		if(0==roleBiz.deleteRole(id,version)){
			throw BizException.DB_UPDATE_RESULT_0.newInstance("删除失败!");
		}
	}
}